package org.neframework.webtest.util.file;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;

import org.apache.commons.fileupload.FileItem;
import org.neframework.webtest.model.t_fk_file;
import org.neframework.webtest.util.config.Config;
import org.neframework.webtest.util.date.DateTools;

import com.tmsps.neframework.core.utils.ChkTools;
import com.tmsps.neframework.jpa.sql.OrmComponent;

public class FileTools {

	public static String getSuffix(String filename) {
		if (ChkTools.isNull(filename)) {
			return "";
		}
		if (!filename.contains(".")) {
			return "";
		}
		return filename.substring(filename.lastIndexOf(".") + 1);
	}

	public static void main(String[] args) {
		String s = "x.ds";
		System.err.println(FileTools.getSuffix(s));

	}

	// 上传到 t_fk_file
	public static t_fk_file processUploadedFile(String fileFolder,
			FileItem item, OrmComponent oc) {
		// TODO 处理文件上传
		String fieldName = item.getFieldName();
		String fileName = item.getName();
		String contentType = item.getContentType();
		boolean isInMemory = item.isInMemory();
		long sizeInBytes = item.getSize();

		String suffix = FileTools.getSuffix(fileName);
		String filename = System.currentTimeMillis() + "." + suffix;

		int year = DateTools.getYear();
		int month = DateTools.getMonth();
		String folder = year + File.separator + month;
		String folder_url = year + "/" + month;

		// 保存文件
		t_fk_file tf = new t_fk_file();
		tf.setFile_name(fileName);
		tf.setNew_file_name(filename);
		tf.setFolder(folder);
		tf.setFolder_url(folder_url);
		tf.setContent_type(contentType);
		tf.setIsize(sizeInBytes);

		// File newFile = new File(Config.getConfig().DATA_PATH + File.separator
		// + folder + File.separator + tf.getNew_file_name());
		File newFile = new File(fileFolder + File.separator + folder
				+ File.separator + tf.getNew_file_name());
		
		System.err.println(newFile.getAbsolutePath());
		if (!newFile.getParentFile().exists()) {
			newFile.getParentFile().mkdirs();
		}
		try {
			item.write(newFile);
			oc.saveObj(tf);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return tf;
	}

	// 上传到目录
	public static File processUploadedFile(FileItem item, File outPath) {
		// TODO 处理文件上传
		String fileName = item.getName();

		File newFile = new File(outPath, fileName);
		if (!newFile.getParentFile().exists()) {
			newFile.getParentFile().mkdirs();
		}
		try {
			item.write(newFile);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return newFile;
	}

	// 关闭所有文件
	public static void close(Closeable... oo) {
		for (Closeable closeable : oo) {
			try {
				if (closeable != null) {
					closeable.close();
				}
			} catch (IOException e) {
			}
		}
	}

}
